<?php

declare(strict_types=1);

namespace app\admin\service\system;

use app\common\model\auth\AdminModel;
use app\common\model\system\PluginModel;
use Dengje\Pxy\BaseService;
use dengje\jwt\facade\JWTAuth;
use think\facade\Cache;
use think\facade\Console;

class PluginService extends BaseService
{

    public function install($plugin,$version)
    {
        if(PluginModel::where('name', $plugin)->find()){
            throw new \Exception('插件已安装');
      
        }
       
        app()->plugin->getPlug($plugin)->install();

        // 迁移文件执行
        if(is_dir(root_path()."plugin/{$plugin}/database/migrations/")){
            copy_directory(root_path()."plugin/{$plugin}/database/migrations/",root_path()."database/migrations/");
        }
        $output = \think\facade\Console::call('migrate:run',[]);

        PluginModel::create(['name' => $plugin,'version'=>$version, 'status' => 1]);
        Cache::delete('menu');
        return true;
    }

    public function uninstall($plugin)
    {
        if(!PluginModel::where('name', $plugin)->find()){
            throw new \Exception('插件未安装');
        }
        app()->plugin->getPlug($plugin)->unInstall();
        PluginModel::where('name', $plugin)->delete();
        delete_directory(root_path()."plugin".DIRECTORY_SEPARATOR."{$plugin}");
        Cache::delete('menu');
        return true;
    }


    public function update($plugin,$version)
    {
        if(!PluginModel::where('name', $plugin)->find()){
            throw new \Exception('插件未安装');
        }
        app()->plugin->getPlug($plugin)->update();
        PluginModel::where('name', $plugin)->update(['version'=>$version]);
        Cache::delete('menu');
        return true;
    }

    public function enable($plugin)
    {
        if(!PluginModel::where('name', $plugin)->find()){
            throw new \Exception('插件未安装');
        }
        app()->plugin->getPlug($plugin)->enable();
        $pluginInfo =  PluginModel::where('name', $plugin)->find();
        $pluginInfo->status = 1;
        $pluginInfo->save();
        Cache::delete('menu'); 
        return true;
       
    }

    public function disable($plugin)
    {
        if(!PluginModel::where('name', $plugin)->find()){
            throw new \Exception('插件未安装');
        }
        app()->plugin->getPlug($plugin)->disable();
        $pluginInfo =  PluginModel::where('name', $plugin)->find();
        $pluginInfo->status = 0;
        $pluginInfo->save();
        Cache::delete('menu');
        return true;
       
    }

    public function updateSystem()
    {
        Cache::delete('menu');
        Console::call('migrate:run');
        return true;
    }
}